package main

import (
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var listen *string
var port *int

func init() {
	//profile := flag.String("profile", "local", "运行环境: local, test, prod")
	//dataCenterAddress := flag.String("dcAddr", "127.0.0.1:8500", "配置中心连接地址")
	//dataCenter := flag.String("dc", "dc1", "配置中心名")
	listen = flag.String("l", "0.0.0.0", "监听地址")
	port = flag.Int("p", 8063, "端口")

	flag.Parse()

}

func main() {

	http.HandleFunc("/sync/getServer", frameSync)

	go CManager.Start()
	log.Println("开启客户端管理")

	addr := fmt.Sprintf("%s:%d", *listen, *port)
	log.Printf("开启服务 [%s]\n", addr)

	err := http.ListenAndServe(addr, nil)

	if err != nil {
		log.Println(err)
	}
}

func frameSync(res http.ResponseWriter, r *http.Request) {

	conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		return true
	}}).Upgrade(res, r, nil)

	if err != nil {
		log.Println("建立链接失败", err)
		return
	}

	client := &Client{
		Socket: conn,
		Send:   make(chan []byte),
	}

	go client.Read()
	go client.Write()

}
